package com.jackeysun.log

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader

/**
 *   Created by sunxunchao on 2021/12/10.
 */
class LogHelper(file: File) {
    val logFile = File(file.absolutePath, "log${System.currentTimeMillis()}.log")

    init {
        val mPId = android.os.Process.myPid()
        val cmd = "logcat -v threadtime | grep $mPId" //打印所有日志信息
//       val cmd = "logcat  | grep $mPId"//打印所有日志信息;
//        val cmd = "logcat -v time"//打印所有日志信息;
        startObserve(cmd, mPId)
    }

    private fun startObserve(cmd: String, mPId: Int) {
        GlobalScope.launch {
            withContext(Dispatchers.IO){
                var logcatProc: Process? = null
                var mReader: BufferedReader? = null
                try {
                    logcatProc = Runtime.getRuntime().exec(cmd)
                    mReader = BufferedReader(InputStreamReader(logcatProc.inputStream), 1024)
                    var line: String? = null
                    while (mReader.readLine().also { line = it } != null) {
                        if (line == null || line?.length == 0) {
                            continue
                        }
                        GlobalScope.launch (Dispatchers.Main){
                            LogConfig.onLogcatListener?.onLogcatInfo("${line}")
                        }
                        "${line}\n".toFile(logFile)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    logcatProc?.destroy()
                    logcatProc = null
                    mReader?.close()
                    logcatProc = null
                }
            }
        }
    }
}